package com.makenv.web.backend;

import com.makenv.domain.User;
import com.makenv.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/manage/user")
public class UserManageController {

    @Autowired
    UserService userService;

    @RequestMapping("/showback")
    public String show(HttpServletRequest request) {

        int sum = userService.getUserSum();
        List<User> userList = userService.showUserList(0, sum);
        request.setAttribute("userList", userList);
        return "back/user";
    }

    @RequestMapping("/add")
    public String add(@RequestParam String username, @RequestParam String password) {

        userService.insert(username, password);
        return "redirect:/manage/user/showback";
    }

    @RequestMapping("/update")
    public String update(@RequestParam int id, @RequestParam String username, @RequestParam String password) {

        userService.updateByPrimaryKey(id, username, password);
        return "redirect:/manage/user/showback";
    }

    @RequestMapping("delete")
    public String delete(@RequestParam String jsonStr) {

        String[] idArray = jsonStr.split(",");
        for (String str : idArray) {
            int i = Integer.valueOf(str);
            userService.deleteByPrimaryKey(i);
        }

        //这个请求是由ajax发送上来的，SpringMVC不会进行页面的跳转，用ajax进行跳转
        return "";
    }
}
